package com.demo2do.fms.admin.web.controller.authority.role;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.demo2do.core.entity.exception.BusinessException;
import com.demo2do.core.entity.page.Page;
import com.demo2do.core.entity.result.HttpResult;
import com.demo2do.core.persistence.support.QueryOrder;
import com.demo2do.core.web.interceptor.MenuSetting;
import com.demo2do.core.web.resolver.Preloading;
import com.demo2do.fms.admin.service.authority.ResourceService;
import com.demo2do.fms.admin.service.authority.RoleService;
import com.demo2do.fms.entity.authority.Resource;
import com.demo2do.fms.entity.authority.ResourceType;
import com.demo2do.fms.entity.authority.Role;
import com.demo2do.fms.entity.authority.RoleTemplate;

/**
 * 角色管理
 * 
 * @author Ysy
 *
 */
@Controller
@RequestMapping("/roles")
@MenuSetting("menu-authority")
public class RoleController {
    
    @Autowired
    private RoleService roleService;
    
    @Autowired
    private ResourceService resourceService;
    
    /**
     * list
     * 
     * @param page
     * @return
     */
    @RequestMapping(value = "", method = RequestMethod.GET)
    @MenuSetting("submenu-role-management")
    public ModelAndView list(Page page){
        
        ModelAndView modelAndView = new ModelAndView("authority/role/role-list");
        
        int totals = roleService.count(Role.class);
        if(totals > 0){
            
            List<Role> roles = roleService.listByPage(Role.class, new QueryOrder("id", "ASC"), page.with(totals));
            
            modelAndView.addObject("roles", roles);
            modelAndView.addObject("page", page);
            
        }
        
        return modelAndView;
        
    }
    
    /**
     * display prepare panel to select role_template
     * 
     * @return
     */
    @RequestMapping(value = "/prepare", method = RequestMethod.GET)
    @MenuSetting("submenu-role-management")
    public ModelAndView prepare(){
        ModelAndView modelAndView = new ModelAndView("authority/role/role-prepare");
        return modelAndView;
    }
    
    /**
     * display create page
     * 
     * @param template
     * @return
     */
    @RequestMapping(value = "/create", method = RequestMethod.GET)
    @MenuSetting("submenu-role-management")
    public ModelAndView create(@RequestParam("template") int template){
        
        ModelAndView modelAndView = new ModelAndView("authority/role/role-create");
        
        RoleTemplate roleTemplate = RoleTemplate.ordinalOf(template);
        
        // 1. find counts of role template and construct 'role_code'
        int roleCode = roleService.count(roleTemplate) + 1;
        
        // 2. find all the menus ( according to this template )
        List<String> menuNames = resourceService.list(roleTemplate, ResourceType.MENU);
        
        // 3. find all the submenus mapped by menu key ( according to this template )
        List<String> submenuNames = resourceService.list(roleTemplate, ResourceType.SUBMENU);

        modelAndView.addObject("roleTemplate", roleTemplate);
        modelAndView.addObject("roleCode", roleTemplate.name() + "_" + roleCode);
        modelAndView.addObject("menuNames", menuNames);
        modelAndView.addObject("submenuNames", submenuNames);
        
        return modelAndView;
    }
    
    /**
     * check if already has the role name
     * 
     * @param roleName
     * @return
     */
    @RequestMapping(value = "", method = RequestMethod.GET, params="exsitName", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public @ResponseBody HttpResult exsitName(@RequestParam(name = "roleName") String roleName){
        
        HttpResult httpResult = new HttpResult();
        
        Boolean existName = roleService.exsitName(roleName);
        
        httpResult.success()
                  .data("existName", existName);
        
        return httpResult;
    }
    
    /**
     * on create
     * 
     * @param role
     * @param menus
     * @return
     */
    @RequestMapping(value = "", method = RequestMethod.POST)
    public ModelAndView onCreate(Role role, @RequestParam(value = "menus") List<String> menus){
        
        ModelAndView modelAndView = new ModelAndView("redirect:/roles");
        
        roleService.create(role, menus);
        
        return modelAndView;
    }
    
    /**
     * 
     * @param id
     * @param page
     * @return
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    @MenuSetting("submenu-role-management")
    public ModelAndView view(@PathVariable("id") Long id, Page page){
        
        ModelAndView modelAndView = new ModelAndView("authority/role/role-view");
        
        Role role = roleService.load(Role.class, id);
        
        int totals = resourceService.count(role);
        
        if(totals > 0){
            
            List<Resource> resources = resourceService.list(role, page.with(totals));
            modelAndView.addObject("resources", resources);
            modelAndView.addObject("page", page);
        }
        
        modelAndView.addObject("role", role);
        modelAndView.addObject("totals", totals);
        
        return modelAndView;
    }
    
    /**
     * display edit info panel
     * 
     * @param id
     * @return
     */
    @RequestMapping(value = "/{id}/edit", method = RequestMethod.GET)
    @MenuSetting("submenu-role-management")
    public ModelAndView edit(@PathVariable("id") Long id){
        
        ModelAndView modelAndView = new ModelAndView("authority/role/role-edit");
        
        Role role = roleService.load(Role.class, id);
        
        modelAndView.addObject("role", role);
        
        return modelAndView;
        
    }
    
    /**
     * on edit info
     * 
     * @param role
     * @return
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.PATCH, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @MenuSetting("submenu-role-management")
    public @ResponseBody HttpResult onEdit(@Preloading("roleId") Role role){
        
        HttpResult httpResult = new HttpResult();
        
        roleService.update(role.operate());
        
        httpResult.success().message("修改基本信息成功");
        
        return httpResult;
        
    }
    
    /**
     * display delete panel
     * 
     * @param id
     * @return
     */
    @RequestMapping(value = "/{id}/delete", method = RequestMethod.GET)
    public ModelAndView delete(@PathVariable("id") Long id) {
        
        ModelAndView modelAndView = new ModelAndView("authority/role/role-delete");
        
        modelAndView.addObject("id", id);
        
        return modelAndView;
        
    }
    
    /**
     * on delete
     * 
     * @param id
     * @return
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public @ResponseBody HttpResult onDelete(@PathVariable("id") Long id){
        
        HttpResult httpResult = new HttpResult();
        
        try{
            
            Role role = roleService.load(Role.class, id);
            
            roleService.disable(role);
            
            httpResult.success().message("删除角色成功！");
            
        } catch(BusinessException e){
            
            httpResult.fail("删除角色失败！").message(e.getMessage());
        }
        
        return httpResult;
        
    }
    
}
